package com.caltco.cargo.ops.common.utils;

import cn.hutool.core.util.ClassUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caltco.cargo.ops.common.annotation.ServiceName;
import com.caltco.cargo.ops.common.autoconfigure.AgileFastConfiguration;
import com.caltco.cargo.ops.common.vo.ServiceNameVo;
import com.caltco.cargo.ops.common.vo.ServiceVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * description: ScanUtils 扫描类
 * date: 2023/2/6 16:15
 * author: yehao
 * version: 1.0
 */
@Component
public class ScanUtils {

    @Resource
    private AgileFastConfiguration agileFastConfiguration;
    @Value("${prefix.name}")
    private String prefix;
    public ServiceVo getServices() {
        ServiceVo serviceVo = new ServiceVo();
        Set<Class<?>> service = ClassUtil.scanPackageBySuper("com.caltco.cargo.ops.modules", ServiceImpl.class);
        if (service.size() > 0 ) {
            List<ServiceNameVo> serviceNames = new ArrayList<>();
            for (Class item : service) {
                ServiceName parent = (ServiceName) item.getAnnotation(ServiceName.class);
                if (Optional.ofNullable(parent).isPresent()) {
                    ServiceNameVo serviceNameVo = new ServiceNameVo();
                    serviceNameVo.setModuleName(parent.value());
                    serviceNameVo.setLabelName(parent.labelName());
                    serviceNameVo.setValueName(parent.valueName());
                    serviceNameVo.setValue(item.getName());
                    serviceNameVo.setPrefix(prefix);
                    serviceNames.add(serviceNameVo);
                }
            }
            serviceVo.setChildren(serviceNames);
        }
        return serviceVo;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param object
     * @return
     */
    public String getFieldValueByFieldName(String fieldName, Object object) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            //设置对象的访问权限，保证对private的属性的访问
            field.setAccessible(true);
            return  (String)field.get(object);
        } catch (Exception e) {
            return null;
        }
    }





}
